import { _decorator, Color, Component, EventTouch, instantiate, Label, Node, Sprite, SpriteFrame } from 'cc';
import { EventManager } from '../event/EventManager';
import { AudioManager, Mp3Enum } from './AudioManager';
const { ccclass, property } = _decorator;

interface TabBtn{
    name:string,
    onClick:Function,
    target:any
}

@ccclass('TabLayout')
export class TabLayout extends Component {

    @property(SpriteFrame)
    btnSpriteFrame1:SpriteFrame
    @property(SpriteFrame)
    btnSpriteFrame2:SpriteFrame
  
    activeNode:Node

    start() {

    }

    setData(list: string[]){
        
        let btn:Node = this.node.children[0]
        for(let ch of this.node.children){
           ch.active = false
        }
        // this.node.destroyAllChildren()

        let nodeList = []
        for(let item of list){
            let node = instantiate(btn)
            nodeList.push(node)
            this.node.addChild(node)
            node.active = true
            node.getChildByName('Label').getComponent(Label).string = item
            node.on(Node.EventType.TOUCH_END, this.onClick, this)
        }

        this.setActive(nodeList[0])
    }

    onClick(e:EventTouch){

        if(e.target == this.activeNode){
            return
        }

        AudioManager.instance.playOneShot(Mp3Enum.mouse_click)
        let label = e.target.getChildByName('Label').getComponent(Label).string
        EventManager.instance.emit(label, 1)

        this.setActive(e.target)
    }

    setActiveByName(name:string){
        
        for(let ch of this.node.children){
            let str = ch.getChildByName('Label').getComponent(Label).string
            if(str == name){
                this.setActive(ch)
            }
         }
    }

     /**
     * 设置按钮的高亮
     */
     setActive(btn: Node) {
        this.activeNode = btn
        for(let ch of this.node.children){
            ch.getComponent(Sprite).spriteFrame = this.btnSpriteFrame2
            ch.getChildByName('Label').getComponent(Label).color = new Color('#908A81')
        }

        btn.getComponent(Sprite).spriteFrame = this.btnSpriteFrame1
        btn.getChildByName('Label').getComponent(Label).color = new Color('#DACAB3')
    }

    setRedDot(name:string, flag:boolean){
        for(let ch of this.node.children){
            let str = ch.getChildByName('Label').getComponent(Label).string
            if(str == name){
                ch.getChildByName('RedDot').active = flag
            }
         }
    }
    
}


